package org.eiahe.hr.attendance.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.ehe.common.core.utils.MapstructUtils;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.system.domain.HrEmployee;
import org.ehe.system.mapper.HrEmployeeMapper;
import org.eiahe.hr.attendance.domain.EmployeeShift;
import org.eiahe.hr.attendance.domain.LeaveApplication;
import org.eiahe.hr.attendance.domain.Shift;
import org.eiahe.hr.attendance.domain.bo.EmployeeShiftBo;
import org.eiahe.hr.attendance.domain.vo.EmployeeShiftVo;
import org.eiahe.hr.attendance.domain.vo.ShiftVo;
import org.eiahe.hr.attendance.mapper.EmployeeShiftMapper;
import org.eiahe.hr.attendance.mapper.ShiftMapper;
import org.eiahe.hr.attendance.service.IEmployeeShiftService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 员工-班次关联服务实现
 *
 * @author zhangnn
 */
@RequiredArgsConstructor
@Service
public class EmployeeShiftServiceImpl implements IEmployeeShiftService {

    private final EmployeeShiftMapper baseMapper;
    private final ShiftMapper shiftMapper;
    private final HrEmployeeMapper employeeMapper;

    /**
     * 查询员工班次关联
     */
    @Override
    public EmployeeShiftVo queryById(Long id) {
        EmployeeShiftVo vo = baseMapper.selectVoById(id);
        if (vo != null && vo.getShiftId() != null) {
            ShiftVo shiftVo = shiftMapper.selectVoById(vo.getShiftId());
            vo.setShiftVo(shiftVo);
            vo.setShiftName(shiftVo != null ? shiftVo.getShiftName() : null);
        }
        return vo;
    }

    /**
     * 查询员工班次关联列表
     */
    @Override
    public List<EmployeeShiftVo> queryList(EmployeeShiftBo bo) {
        LambdaQueryWrapper<EmployeeShift> lqw = buildQueryWrapper(bo);
        List<EmployeeShiftVo> list = baseMapper.selectVoList(lqw);
        // 填充班次信息
        list.forEach(this::fillShiftInfo);
        return list;
    }

    /**
     * 分页查询员工班次关联列表
     */
    @Override
    public TableDataInfo<EmployeeShiftVo> queryPageList(EmployeeShiftBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<EmployeeShift> lqw = buildQueryWrapper(bo);
        Page<EmployeeShiftVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        // 填充班次信息
        result.getRecords().forEach(this::fillShiftInfo);
        return TableDataInfo.build(result);
    }

    private LambdaQueryWrapper<EmployeeShift> buildQueryWrapper(EmployeeShiftBo bo) {
        LambdaQueryWrapper<EmployeeShift> lqw = Wrappers.lambdaQuery();
        //lqw.eq(StringUtils.isNotBlank(bo.getEmployeeNo()), EmployeeShift::getEmployeeNo, bo.getEmployeeNo());
        if (org.apache.commons.lang3.StringUtils.isNotBlank(bo.getEmployeeName())) {
            List<HrEmployee> employees = employeeMapper.selectList(
                Wrappers.lambdaQuery(HrEmployee.class)
                    .like(HrEmployee::getEmployeeName, bo.getEmployeeName()));
            List<String> employeeNos = Optional.ofNullable(employees)
                .orElse(Collections.emptyList())
                .stream()
                .map(HrEmployee::getEmployeeNo)
                .collect(Collectors.toList());

            if (CollUtil.isEmpty(employeeNos)) {
                lqw.eq(EmployeeShift::getEmployeeNo, -1);
            } else {
                lqw.in(EmployeeShift::getEmployeeNo, employeeNos);
            }
        }
        lqw.eq(bo.getUserId() != null, EmployeeShift::getUserId, bo.getUserId());
        lqw.eq(bo.getShiftId() != null, EmployeeShift::getShiftId, bo.getShiftId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), EmployeeShift::getStatus, bo.getStatus());
        lqw.orderByDesc(EmployeeShift::getCreateTime);
        return lqw;
    }

    /**
     * 填充班次信息
     */
    private void fillShiftInfo(EmployeeShiftVo vo) {
        if (vo != null && vo.getShiftId() != null) {
            ShiftVo shiftVo = shiftMapper.selectVoById(vo.getShiftId());
            vo.setShiftVo(shiftVo);
            vo.setShiftName(shiftVo != null ? shiftVo.getShiftName() : null);
        }
        if(StringUtils.isNotBlank(vo.getEmployeeNo())){
            HrEmployee hrEmployee = employeeMapper.selectOne(new LambdaQueryWrapper<HrEmployee>()
                .eq(HrEmployee::getEmployeeNo, vo.getEmployeeNo()));
            if(Objects.nonNull(hrEmployee)){
                vo.setEmployeeName(hrEmployee.getEmployeeName());
            }
        }
    }

    /**
     * 新增员工班次关联
     */
    @Override
    public Boolean insertByBo(EmployeeShiftBo bo) {
        EmployeeShift add = MapstructUtils.convert(bo, EmployeeShift.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改员工班次关联
     */
    @Override
    public Boolean updateByBo(EmployeeShiftBo bo) {
        EmployeeShift update = MapstructUtils.convert(bo, EmployeeShift.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(EmployeeShift entity) {
        // 校验生效日期和失效日期
        if (entity.getEffectiveDate() != null && entity.getExpiryDate() != null) {
            if (entity.getEffectiveDate().isAfter(entity.getExpiryDate())) {
                throw new RuntimeException("生效日期不能晚于失效日期");
            }
        }

        // 校验班次是否存在
        if (entity.getShiftId() != null) {
            Shift shift = shiftMapper.selectById(entity.getShiftId());
            if (shift == null) {
                throw new RuntimeException("班次不存在");
            }
        }
    }

    /**
     * 批量删除员工班次关联
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 批量分配班次给员工
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchAssignShift(List<String> employeeNos, Long shiftId, LocalDate effectiveDate,
            LocalDate expiryDate) {
        if (employeeNos == null || employeeNos.isEmpty()) {
            throw new RuntimeException("员工列表不能为空");
        }
        if (shiftId == null) {
            throw new RuntimeException("班次ID不能为空");
        }
        if (effectiveDate == null) {
            throw new RuntimeException("生效日期不能为空");
        }

        // 校验班次是否存在
        Shift shift = shiftMapper.selectById(shiftId);
        if (shift == null) {
            throw new RuntimeException("班次不存在");
        }

        List<EmployeeShift> list = new ArrayList<>();
        for (String employeeNo : employeeNos) {
            EmployeeShift employeeShift = new EmployeeShift();
            employeeShift.setEmployeeNo(employeeNo);

            HrEmployee hrEmployee = employeeMapper.selectOne(new LambdaQueryWrapper<HrEmployee>().eq(HrEmployee::getEmployeeNo, employeeNo));
            if(Objects.nonNull(hrEmployee)){
                employeeShift.setUserId(hrEmployee.getUserId());
            }
            employeeShift.setShiftId(shiftId);
            employeeShift.setEffectiveDate(effectiveDate);
            employeeShift.setExpiryDate(expiryDate);
            employeeShift.setStatus("0");
            list.add(employeeShift);
        }

        // 批量插入
        return baseMapper.insertBatch(list);
    }

    /**
     * 查询员工当前生效的班次
     */
    @Override
    public ShiftVo queryEmployeeCurrentShift(String employeeNo, LocalDate date) {
        if (StringUtils.isBlank(employeeNo)) {
            throw new RuntimeException("员工工号不能为空");
        }
        if (date == null) {
            date = LocalDate.now();
        }

        LambdaQueryWrapper<EmployeeShift> lqw = Wrappers.lambdaQuery();
        lqw.eq(EmployeeShift::getEmployeeNo, employeeNo);
        lqw.eq(EmployeeShift::getStatus, "0"); // 正常状态
        lqw.le(EmployeeShift::getEffectiveDate, date); // 生效日期 <= 查询日期
        // 失效日期为空或失效日期 >= 查询日期
        lqw.and(wrapper -> wrapper.isNull(EmployeeShift::getExpiryDate)
                .or()
                .ge(EmployeeShift::getExpiryDate, LocalDate.now()));
        lqw.orderByDesc(EmployeeShift::getEffectiveDate);
        lqw.last("LIMIT 1");

        EmployeeShift employeeShift = baseMapper.selectOne(lqw);
        if (employeeShift != null && employeeShift.getShiftId() != null) {
            return shiftMapper.selectVoById(employeeShift.getShiftId());
        }
        return null;
    }
}
